const bcrypt = require('bcryptjs')

const { getUserInfo } = require('../service/user.service')
const { userAlreadyExited, userFormateError, userRegisterError, userDoesNotExist, userLoginError, invalidPasswordError } = require('../constant/err.type')
// 合理性 
const userValidator = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    if (!user_name || !password) {
        // ctx.status = 400
        // ctx.body = userFormateError
        ctx.app.emit('error', userFormateError, ctx)
        console.error(userFormateError.message, ctx.request.body)

        return
    }
    await next()
}
// 合法性 
const verifyUser = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    // if (await getUserInfo({ user_name })) {
    //     ctx.app.emit('error', userAlreadyExited, ctx)
    //     console.error(userAlreadyExited.message, ctx.request.body)
    //     return
    // }
    try {
        const res = await getUserInfo({ user_name })
        if (res) {
            console.error('用户名存在！', { user_name })
            ctx.app.emit('error', userAlreadyExited, ctx)
            return
        }
    } catch (err) {
        console.error('获取用户信息错误!', err)
        ctx.app.emit('error', userRegisterError, ctx)
        return
    }
    await next()
}
// 密码加密
const cryptPassword = async (ctx, next) => {
    const { password } = ctx.request.body
    // 盐 注意细节好吧
    const salt = bcrypt.genSaltSync(10)
    // 
    const hash = bcrypt.hashSync(password, salt)
    //
    ctx.request.body.password = hash
    await next()
}

const verifyLogin = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    // 验证用户是否存在
    try {
        const res = await getUserInfo({ user_name })
        if (!res) {
            console.error('用户不存在！', { user_name })
            return ctx.app.emit('error', userDoesNotExist, ctx)
        }
        // 验证密码是否匹配
        if (!bcrypt.compareSync(password, res.password)) {
            return ctx.app.emit('error', invalidPasswordError, ctx)
        }
    } catch (err) {
        console.log(err)
        return ctx.app.emit('error', userLoginError, ctx)

    }
    await next()
}
module.exports = {
    userValidator,
    verifyUser,
    cryptPassword,
    verifyLogin
}